import { changePwd, outLogin } from '@/services/api_user';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Form, Modal, Spin } from 'antd';
import { createStyles } from 'antd-style';
import { stringify } from 'querystring';
import React, { useCallback, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from './HeaderDropdown';
import { ModalForm, ProFormText, ProFormInstance } from '@ant-design/pro-components';


export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.name}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    await outLogin();
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    };
    // 需要刷新后才能显示 登录页面
    window.location.reload();
  };
  const { styles } = useStyles();

  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: { key: string }) => {
      const { key } = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        loginOut();
        return;
      }
      if (key === 'settings') {
        // history.push('/user/changePWD');
        setModalOpen(true);
        return;
      }
    },
    [setInitialState],
  );

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  const menuItems = [
    ...[
      // {
      // 	key: 'center',
      // 	icon: <UserOutlined />,
      // 	label: '个人中心',
      // },
      {
        key: 'settings',
        icon: <SettingOutlined />,
        label: '修改密码',
      },
      {
        type: 'divider' as const,
      },
    ],
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  const [modalOpen, setModalOpen] = useState(false);
  const formRef = useRef<ProFormInstance>();

  const handleOk = async (values: any) => {
    changePwd(values.oldPassword, values.newPassword).then((res) => {
      if (res) {
        Modal.success({
          title: '修改密码成功',
        });
        formRef.current?.resetFields();
        setModalOpen(false);
      }
    });
    formRef.current?.resetFields();
  };

  return (
    <div>
      <ModalForm
        formRef={formRef}
        title="修改密码"
        open={modalOpen}
        onFinish={handleOk}
        modalProps={{ destroyOnClose: true, onCancel: () => setModalOpen(false) }} // 关闭弹窗时销毁子元素
      >
        <ProFormText.Password
          name="oldPassword"
          label="旧密码"
          rules={[{ required: true, message: '请输入旧密码' }]}
        />
        <ProFormText.Password
          name="newPassword"
          label="新密码"
          rules={[{ required: true, message: '请输入新密码' }]}
        />
        <ProFormText.Password
          name="confirmPassword"
          label="确认密码"
          dependencies={['newPassword']}
          rules={[
            {
              required: true,
              message: '请确认新密码',
            },
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject('确认密码与新密码不一致');
              },
            }),
          ]}
        />
      </ModalForm>

      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        {/* 报错 React.Children.only expected to receive a single React element child */}
        {(children as [React.ReactNode])[0]}
      </HeaderDropdown>
    </div>
  );
};
